/*
 * Copyright (c) csii.com.cn 2016 zhaojin
 */

package com.csii.ssm.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhaojin on 16/5/1.
 */
public class RequestURLFilter implements Filter {

    private String errorPageFile;
    private Pattern pattern;

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String absPath;
        if ("POST".equals(request.getMethod())) {
            absPath = this.connPOSTParameters(req);
        } else {
            absPath = request.getQueryString();
        }

        if (absPath != null && absPath.trim().length() != 0) {
            Matcher m = this.pattern.matcher(absPath);
            if (m.find()) {
                if (this.errorPageFile != null) {
                    RequestDispatcher dispatcher = req.getRequestDispatcher(this.errorPageFile);
                    dispatcher.forward(request, response);
                } else {
                    throw new ServletException("invalid input characters");
                }
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    public void init(FilterConfig config) throws ServletException {
        String regExpr = config.getInitParameter("invalidCharacters");
        if (regExpr != null && regExpr.trim().length() > 0) {
            this.pattern = Pattern.compile(regExpr);
            this.errorPageFile = config.getInitParameter("errorPageFile");
        } else {
            throw new ServletException("RequestURlFilter need to set initial parameter:invalidCharacters");
        }
    }

    private String connPOSTParameters(ServletRequest request) {
        StringBuffer pbuffer = new StringBuffer();
        Enumeration names = request.getParameterNames();

        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            pbuffer.append(name).append(request.getParameter(name));
        }

        return pbuffer.toString();
    }

}
